
package com.jianganming.netty;

import com.alibaba.fastjson.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.util.Scanner;
import java.util.concurrent.TimeUnit;

//服务端处理器
public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    //读取客户端数据
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf)msg;
        String messge = byteBuf.toString(CharsetUtil.UTF_8);
        JSONObject jsonObject = JSONObject.parseObject(messge);
        System.out.println(jsonObject.getString("name")+"   说：");
        System.out.println(jsonObject.getString("msg"));
        //开启新的线程，向客户端发消息
        ctx.channel().eventLoop().execute(()->{
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNext()){
                ctx.writeAndFlush(Unpooled.copiedBuffer(scanner.next(),CharsetUtil.UTF_8));
            }

        });
    }

    //向客户端写数据
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello,客户端...",CharsetUtil.UTF_8));
    }

    //异常处理
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        ctx.close();
    }
}
